// 配置参数
const selectors = [
  {
    selector: "#btn1",
    message: "点此【新增】数据",
  },
  {
    selector: "#btn2",
    message: "小心【删除】数据",
  },
  {
    selector: "#btn3",
    message: "点此【修改】数据",
  },
  {
    selector: "#btn4",
    message: "一键完成所有操作",
  },
  {
    selector: "#btn5",
    message: "btn5",
  },
  {
    selector: "#btn6",
    message: "btn6",
  },
  {
    selector: "#btn7",
    message: "btn7",
  },
];

const windowWidth = document.documentElement.clientWidth;
const windowHeight = document.documentElement.clientHeight;
const guideBox = document.getElementById("guideBox");
const guideMessage = document.getElementById("guideMessage");
const guidePrevBtn = document.getElementById("guidePrevBtn");
const guideNextBtn = document.getElementById("guideNextBtn");
const mask = document.getElementById("mask");

let preNode = null;
let index = 0;
let show = true;

document.addEventListener("DOMContentLoaded", () => {
  genGuide();
});

// 页面内容发生变化时，重新计算位置
window.addEventListener("resize", () => genGuide());
window.addEventListener("scroll", () => genGuide());

guidePrevBtn.addEventListener("click", () => {
  changeStep(true);
});

guideNextBtn.addEventListener("click", () => {
  changeStep(false);
});

function changeStep(isPre) {
  isPre ? index-- : index++;
  genGuide();
}

function genGuide() {
  // 所有指引完毕
  if (index > selectors.length - 1) {
    show = false;

    return;
  }

  // 获取目标节点信息
  const target = (preNode = document.querySelector(selectors[index].selector));
  const { x, y, width, height } = target.getBoundingClientRect();
  // 设置svg
  updateHighlight({ x, y, width, height });

  // 指引相关
  if (guideBox) {
    const halfClientHeight = guideBox.clientHeight / 2;
    guideMessage.innerText = selectors[index].message;

    const right = windowWidth;
    const bottom = windowHeight;
    let guideBoxLeft;
    let guideBoxTop;

    if (right - (x + width) < guideBox.clientWidth) {
      guideBoxLeft = x - 10 - guideBox.clientWidth;
    } else {
      guideBoxLeft = x + width + 10;
    }

    if (y <= halfClientHeight) {
      guideBoxTop = y;
    } else if (bottom - (y + height) < halfClientHeight) {
      guideBoxTop = y + height - guideBox.clientHeight;
    } else {
      guideBoxTop = y + height / 2 - halfClientHeight;
    }

    guideBox.style = `left:${guideBoxLeft}px;top:${guideBoxTop}px`;
  }
}

/**
 * 高亮元素
 *
 * @param {object} param0 x-高亮元素的x坐标，y-高亮元素的y坐标，width-高亮元素的宽度，height-高亮元素的高度
 */
function updateHighlight({ x, y, width, height }) {
  const path = mask.querySelector("path");
  path.setAttribute(
    "d",
    `M ${windowWidth} ${windowHeight} H 0 V 0 H ${windowWidth} V ${windowHeight} Z M ${x} ${y} V ${y + height} H ${
      x + width
    } V ${y} Z`
  );
}
